import React, { Component } from 'react';
import { connect } from 'dva';
import styles from './index.css';
import { produce, Draft } from 'immer';
import { DEFAULT_PAGE_NUM, DEFAULT_PAGE_SIZE } from '@/const';
import { Dispatch, AnyAction } from 'redux';
import { Button, Table, DatePicker, Input, Select, Pagination, message } from 'antd';
import locale from 'antd/lib/date-picker/locale/zh_CN';
import { isMenuVisible } from '@/utils/utils';
import moment from 'moment';
import 'moment/locale/zh-cn';
moment.locale('zh-cn');
import _ from 'lodash';

const { Option } = Select;

interface callpoliceManageListPsops {
  loading: boolean;
  dispatch: Dispatch<AnyAction>;
  deviceTypeNo: number;
  deviceSonTypeNo: number;
  childList: any[];
}
interface DetailState {
  filterQueryParams: any;
}
class CallpoliceManageList extends Component<callpoliceManageListPsops, DetailState> {
  state: DetailState = {
    filterQueryParams: {
      deviceTypeParentNo: this.props.deviceTypeParentNo || undefined, // 报警所属类别
      deviceTypeNo: this.props.deviceTypeNo || undefined, // 报警资产种类
      deviceId: this.props.deviceId || '', //资产编号
      deviceName: '', //设备名称
      startTime: '', // 开始采集时间
      endTime: '', // 结束采集时间
      pageNum: DEFAULT_PAGE_NUM,
      pageSize: 10,
    },
    value: '',
  };
  handleInputCountChange = (e: string) => {
    // 资产类别
    this.setState(
      produce((draft: Draft<DetailState>): void => {
        draft.filterQueryParams.deviceTypeParentNo = e;
        draft.filterQueryParams.deviceTypeNo = '';
      }),
    );
    const { dispatch } = this.props;
    if (e) {
      dispatch({ type: 'device/matchChildsByParents', payload: { deviceTypeNo: e } });
    } else {
      dispatch({ type: 'device/clearChildren' });
    }
  };
  handleInputTypeChange = (e: string) => {
    // 资产种类
    if (!this.state.filterQueryParams.deviceTypeParentNo) {
      // alert('')
      message.info('请先选择所属类别');
      return;
    } else {
      this.setState(
        produce((draft: Draft<DetailState>): void => {
          draft.filterQueryParams.deviceTypeNo = e;
        }),
      );
    }
  };
  handleInputIDChange = (e: string) => {
    // debugger;
    const reg = /^-?(0|[1-9][0-9]*)(\.[0-9]*)?$/;
    if (
      (!isNaN(e.target.value) && reg.test(e.target.value)) ||
      e.target.value === '' ||
      e.target.value === '-'
    ) {
      e.persist();
      this.setState(
        produce((draft: Draft<DetailState>): void => {
          draft.filterQueryParams.deviceId = e.target.value;
          draft.value = e.target.value;
        }),
      );
    } else {
      this.setState(
        produce((draft: Draft<DetailState>): void => {
          draft.filterQueryParams.deviceId = '';
          draft.value = '';
        }),
      );
    }
  };
  handleInputNameChange = (e: string) => {
    // 设备名称
    e.persist();
    this.setState(
      produce((draft: Draft<DetailState>): void => {
        draft.filterQueryParams.deviceName = e.target.value;
      }),
    );
  };
  handleStartOpenChange = (date: any, dateString: any) => {
    // 开始时间
    this.setState(
      produce((draft: Draft<DetailState>): void => {
        draft.filterQueryParams.startTime = dateString;
      }),
    );
  };
  handleEndOpenChange = (date: any, dateString: any) => {
    // 结束时间
    this.setState(
      produce((draft: Draft<DetailState>): void => {
        draft.filterQueryParams.endTime = dateString;
      }),
    );
  };
  // 页码变化
  handlePageChange: (pageNum: number, pageSize: number | undefined) => void = pageNum => {
    this.setState(
      produce((draft: Draft<ListState>): void => {
        draft.filterQueryParams.pageNum = pageNum;
      }),
      () => isMenuVisible('iot:deviceAlam:monitorAnalyze') && this.handleFilterQuery(),
    );
  };
  handleFilterQuery = () => {
    // 搜索
    console.log(this.state.filterQueryParams);
    const { dispatch } = this.props;
    dispatch({ type: 'deviceWarn/deviceWarnedList', payload: this.state.filterQueryParams });
  };
  componentWillReceiveProps(next) {
    if (this.props.isUpdate !== next.isUpdate) {
      this.setState(
        produce((draft: Draft<ListState>): void => {
          draft.filterQueryParams.deviceTypeParentNo = this.props.deviceTypeParentNo || undefined; // 报警所属类别
          draft.filterQueryParams.deviceTypeNo = this.props.deviceTypeNo || undefined; // 报警资产种类
          draft.filterQueryParams.deviceId = this.props.deviceId || ''; //资产编号
          draft.filterQueryParams.deviceName = ''; //设备名称
          draft.filterQueryParams.startTime = ''; // 开始采集时间
          draft.filterQueryParams.endTime = ''; // 结束采集时间
        }),
      );
    }
  }
  componentWillMount() {
    const { dispatch, deviceTypeNo, deviceTypeParentNo } = this.props;
    dispatch({ type: 'deviceWarn/deviceWarnedTimes' });
    dispatch({ type: 'statistics/longDeviceType' });
    if (deviceTypeNo && deviceTypeParentNo) {
      dispatch({ type: 'device/matchChildsByParents', payload: {  deviceTypeNo: deviceTypeParentNo } });
    }
    isMenuVisible('iot:deviceAlam:monitorAnalyze') && this.handleFilterQuery();
    dispatch({ type: 'device/clearChildren' });
  }
  columns: any = [
    {
      title: '资产编号',
      dataIndex: 'deviceId',
      key: 'deviceId',
    },
    {
      title: '设备名称',
      dataIndex: 'deviceName',
      key: 'deviceName',
    },
    {
      title: '资产类别',
      dataIndex: 'deviceTypeParentName',
      key: 'deviceTypeParentName',
    },
    {
      title: '资产种类',
      dataIndex: 'deviceTypeName',
      key: 'deviceTypeName',
    },
    {
      title: '安装位置',
      dataIndex: 'treeName',
      key: 'treeName',
    },
    {
      title: '发生时间',
      dataIndex: 'happenTime',
      key: 'happenTime',
    },
    {
      title: '上报时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: '报警内容',
      dataIndex: 'alamContent',
      key: 'alamContent',
    },
  ];
  render() {
    const { deviceWarnList, deviceWarnInfo, longDeviceType, childList } = this.props;
    return (
      <div className={styles['inforStatic-container']}>
        {
          <>
            <div className={styles.statistics}>
              <div className={styles.sitem}>
                <div className={styles.simg}>
                  <span>{deviceWarnInfo.dayCount}</span>
                </div>
                <div className={styles.stext}>
                  <span>今日</span>
                </div>
              </div>
              <div className={styles.sitem}>
                <div className={styles.simg}>
                  <span>{deviceWarnInfo.weekCount}</span>
                </div>
                <div className={styles.stext}>
                  <span>近一周</span>
                </div>
              </div>
              <div className={styles.sitem}>
                <div className={styles.simg}>
                  <span>{deviceWarnInfo.monthCount}</span>
                </div>
                <div className={styles.stext}>
                  <span>近30天</span>
                </div>
              </div>
            </div>
            <div className={styles.comList}>
              <div style={{ clear: 'both' }}>
                <div className={styles['dev-search']}>
                  <div className={styles['dev-search-select']}>
                    <Input
                      onChange={this.handleInputIDChange}
                      value={this.state.filterQueryParams.deviceId}
                      addonBefore="资产编号"
                      placeholder="请输入资产编号"
                      type="text"
                    />
                  </div>
                  <div className={styles['dev-search-select']}>
                    <Input
                      onChange={this.handleInputNameChange}
                      placeholder="请输入设备名称"
                      value={this.state.filterQueryParams.deviceName}
                      addonBefore="设备名称"
                      type="text"
                    />
                  </div>
                  <div className={styles['dev-search-select']}>
                    {/* <Input
                  onChange={this.handleInputCountChange}
                  addonBefore="报警所属类别"
                  type="text"
                /> */}
                    <span className={styles['dev-search-select-title']}>资产类别</span>

                    <Select
                      placeholder="请选择资产类别"
                      value={this.state.filterQueryParams.deviceTypeParentNo}
                      style={{ width: 200 }}
                      allowClear={true}
                      onChange={this.handleInputCountChange}
                    >
                      {/* <Option value="">请选择</Option> */}
                      {_.map(longDeviceType, (item: any, index: number) => (
                        <Option key={index} value={item.deviceTypeNo}>
                          {item.deviceTypeName}
                        </Option>
                      ))}
                    </Select>
                  </div>
                  <div className={styles['dev-search-select']}>
                    <span className={styles['dev-search-select-title']}>资产种类</span>

                    <Select
                      placeholder="请先选择资产类别"
                      value={this.state.filterQueryParams.deviceTypeNo}
                      style={{ width: 200 }}
                      allowClear={true}
                      onChange={this.handleInputTypeChange}
                    >
                      {/* <Option value="">请选择</Option> */}
                      {_.map(childList, (item: any, index: number) => (
                        <Option key={index} value={item.deviceTypeNo}>
                          {item.deviceTypeName}
                        </Option>
                      ))}
                    </Select>
                  </div>
                  <div className={styles['dev-search-select-date']}>
                    <span className={styles['dev-search-select-title']}>发生时间</span>
                    <DatePicker
                      className="right_timer_box"
                      onChange={this.handleStartOpenChange}
                      value={
                        this.state.filterQueryParams.startTime
                          ? moment(this.state.filterQueryParams.startTime)
                          : undefined
                      }
                      // defaultPickerValue={this.state.filterQueryParams.startTime}
                      placeholder="开始时间"
                      locale={locale}
                    />
                    <DatePicker
                      className="left_timer_box"
                      placeholder="结束时间"
                      value={
                        this.state.filterQueryParams.endTime
                          ? moment(this.state.filterQueryParams.endTime)
                          : undefined
                      }
                      // defaultPickerValue={this.state.filterQueryParams.endTime}
                      onChange={this.handleEndOpenChange}
                      locale={locale}
                    />
                  </div>
                  <div className={styles.btnArea}>
                    {isMenuVisible('iot:deviceAlam:monitorAnalyze') && (
                      <Button
                        type="link"
                        className={styles['search']}
                        onClick={() => {
                          this.setState(
                            produce((draft: Draft<ListState>): void => {
                              draft.filterQueryParams.pageNum = 1;
                            }),
                            () => {
                              this.handleFilterQuery();
                            },
                          );
                        }}
                      >
                        搜索
                      </Button>
                    )}
                    <Button
                      type="link"
                      className={styles['search']}
                      onClick={() => {
                        this.setState(
                          produce((draft: Draft): void => {
                            draft.filterQueryParams.deviceId = '';
                            draft.filterQueryParams.deviceName = '';
                            draft.filterQueryParams.deviceTypeParentNo = undefined;
                            draft.filterQueryParams.deviceTypeNo = undefined;
                            draft.filterQueryParams.startTime = '';
                            draft.filterQueryParams.endTime = '';
                          }),
                        );
                        const { dispatch } = this.props;
                        dispatch({ type: 'device/clearChildren' });
                      }}
                    >
                      重置
                    </Button>
                  </div>
                </div>
              </div>
              <Table
                scroll={{ y: '500px' }}
                pagination={false}
                columns={this.columns}
                dataSource={deviceWarnList ? deviceWarnList.rows : []}
                rowKey={new Date().getTime() + ''}
              />
              <div className="pagination-box">
                <Pagination
                  // style={{ marginTop: '115px' }}
                  className="call-police-page"
                  defaultCurrent={this.state.filterQueryParams.pageNum}
                  current={this.state.filterQueryParams.pageNum}
                  onChange={this.handlePageChange}
                  total={deviceWarnList.total ? deviceWarnList.total : 0}
                />
                <span className="pagination-title-box">
                  第{this.state.filterQueryParams.pageNum}/
                  {Math.ceil(
                    (deviceWarnList.total ? deviceWarnList.total : 0) /
                      this.state.filterQueryParams.pageSize,
                  )}
                  页 共{deviceWarnList.total ? deviceWarnList.total : 0}条
                </span>
              </div>
            </div>
          </>
        }
      </div>
    );
  }
}
export default connect(({ loading, deviceWarn, statistics, device }: any) => ({
  deviceWarnInfo: deviceWarn.deviceWarnedTimes,
  deviceWarnList: deviceWarn.deviceWarnedList,
  longDeviceType: statistics.longDeviceType,
  childList: device.matchChildsByParents,
}))(CallpoliceManageList);
